package j2024.j202409;

import java.util.Arrays;

public class j0908 {
    /**
     * 1005. K 次取反后最大化的数组和
     * @param nums
     * @param k
     * @return
     */
    public int largestSumAfterKNegations(int[] nums, int k) {
        int n = nums.length;
        int downZero = 0;
        for (int i = 0; i < n; i++) {
            if(nums[i]<0){
                downZero++;
            }
        }
        int ret = 0;
        if(downZero>k){
            Arrays.sort(nums);
            for (int i = 0; i < k; i++) {
                nums[i] = -nums[i];
            }
            for (int i = 0; i < n; i++) {
                ret+=nums[i];
            }
        }else if(downZero==k){
            for (int i = 0; i < n; i++) {
                if(nums[i]<0){
                    ret+=-nums[i];
                }else {
                    ret+=nums[i];
                }
            }
        }else {
            int kk = k-downZero;
            if(kk%2==0){
                for (int i = 0; i < n; i++) {
                    if(nums[i]<0){
                        ret+=-nums[i];
                    }else {
                        ret+=nums[i];
                    }
                }
            }else {
                Arrays.sort(nums);
                for (int i = 0; i < downZero; i++) {
                    if(nums[i]<0){
                        nums[i] = -nums[i];
                    }
                }
                Arrays.sort(nums);
                nums[0] = -nums[0];
                for (int i = 0; i < n; i++) {
                    ret+=nums[i];
                }
            }
        }
        return ret;
    }

    /**
     * 2418. 按身高排序
     * @param names
     * @param heights
     * @return
     */
    public String[] sortPeople(String[] names, int[] heights) {
        int n = heights.length;
        Integer[] index = new Integer[n];
        for (int i = 0; i < n; i++) {
            index[i] = i;
        }
        Arrays.sort(index,(i,j)->{
            return heights[j]-heights[i];
        });
        String[] ret = new String[n];
        for (int i = 0; i < n; i++) {
            ret[i] = names[index[i]];
        }
        return ret;
    }

    /**
     * 870. 优势洗牌
     * @param nums1
     * @param nums2
     * @return
     */
    public int[] advantageCount(int[] nums1, int[] nums2) {
        int n = nums1.length;
        Integer[] index = new Integer[n];
        Arrays.sort(nums1);
        for (int i = 0; i < n; i++) {
            index[i] = i;
        }
        Arrays.sort(index,(i,j)->{
            return nums2[i] - nums2[j];
        });
        int[] ret = new int[n];
        int left = 0,right = n-1;
        for(int a:nums1){
           if(a>nums2[index[left]]){
               ret[index[left]] = a;
               left++;
           }else {
               ret[index[right]] = a;
               right--;
           }
        }
        return ret;
    }
}
